$(document).ready(function() {
    let portfolios = [];
    let totalPages = 1;
    let currentPage = 1;
    let itemsPerPage = 10;
    let selectedPortfolio = null;
    let fundList = []; // 用于存储基金列表

    // 自定义alert函数
    function customAlert(message) {
        $('#customAlertMessage').text(message);
        $('#customAlertModal').modal('show');
    }

    // 获取基金列表用于搜索建议
    function fetchFundsForSearch(fundCode, callback) {
        $.ajax({
            url: `/api/funds/getFundsByConditions`,
            type: 'GET',
            data: {
                fundCode: fundCode || '',
                pageSize: 10
            },
            success: function(data) {
                if (data && data.records) {
                    fundList = data.records;
                    if (callback) callback(fundList);
                }
            },
            error: function(xhr, status, error) {
                console.error('Error fetching funds:', error);
            }
        });
    }

    function fetchPortfolios() {
        const portfolioName = $('#searchPortfolioName').val();
        itemsPerPage = parseInt($('#itemsPerPage').val(), 10);
        const queryParams = {
            portfolioName: portfolioName || '',
            pageNo: currentPage,
            pageSize: itemsPerPage
        };

        $.ajax({
            url: `/api/portfolios/getPortfoliosByConditions`,
            type: 'GET',
            data: queryParams,
            success: function(data) {
                if (!data || !data.records) {
                    console.error('Invalid data received:', data);
                    customAlert('获取数据失败，请检查输入条件或稍后重试。');
                    return;
                }

                portfolios = data.records;
                totalPages = data.pages;
                renderPortfolioTable(portfolios);
                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching portfolios:', error);
                customAlert('获取数据失败，请检查网络连接或稍后重试。');
            }
        });
    }

    function renderPortfolioTable(data) {
        const portfolioTableBody = $('#portfolioTableBody');
        portfolioTableBody.empty();

        if (data.length > 0) {
            data.forEach(portfolio => {
                const tr = $('<tr>');
                tr.append($('<td>').text(portfolio.portfolioName));
                tr.append($('<td>').text(portfolio.description || ''));
                tr.append($('<td>').text(portfolio.createdTime || ''));
                tr.append($('<td>').text(portfolio.updatedTime || ''));
                tr.append($('<td>').text(portfolio.totalValue || '0.00'));
                tr.append($('<td>').text(portfolio.totalCost || '0.00'));
                tr.append($('<td>').text(portfolio.totalProfit || '0.00'));
                tr.append($('<td>').text((portfolio.totalProfitRate || 0) + '%'));
                
                const actionsTd = $('<td>');
                actionsTd.html(`
                    <button class="btn btn-sm btn-warning me-2" onclick="editPortfolio(${portfolio.id})">编辑</button>
                    <button class="btn btn-sm btn-danger me-2" onclick="deletePortfolio(${portfolio.id})">删除</button>
                    <button class="btn btn-sm btn-info" onclick="showPortfolio(${portfolio.id})">详情</button>
                `);
                tr.append(actionsTd);
                portfolioTableBody.append(tr);
            });
        } else {
            portfolioTableBody.html('<tr><td colspan="9" class="text-center">暂无数据</td></tr>');
        }
    }

    // 更新分页控件
    function updatePagination() {
        $('#currentPage').text(currentPage);
        $('#totalPages').text(totalPages);

        // 更新上一页和下一页按钮状态
        if (currentPage <= 1) {
            $('#prevPage').addClass('disabled');
        } else {
            $('#prevPage').removeClass('disabled');
        }

        if (currentPage >= totalPages) {
            $('#nextPage').addClass('disabled');
        } else {
            $('#nextPage').removeClass('disabled');
        }
    }

    function handleSizeChange(newSize) {
        itemsPerPage = newSize;
        currentPage = 1; // 重置到第一页
        fetchPortfolios();
    }

    function handleCurrentChange(newPage) {
        // 确保页码在有效范围内
        if (newPage < 1) newPage = 1;
        if (newPage > totalPages) newPage = totalPages;
        
        if (newPage !== currentPage) {
            currentPage = newPage;
            fetchPortfolios();
        }
    }

    function addNewPortfolio() {
        const portfolioName = $('#addPortfolioName').val();
        const description = $('#addPortfolioDescription').val();

        if (portfolioName.trim() === '') {
            customAlert('组合名称不能为空');
            return;
        }

        const newPortfolio = {
            portfolioName: portfolioName,
            description: description
        };

        $.ajax({
            url: `/api/portfolios/addPortfolio`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(newPortfolio),
            success: function(data) {
                $('#addPortfolioForm')[0].reset();
                $('#addPortfolioModal').modal('hide');
                fetchPortfolios();
                customAlert('新增成功');
            },
            error: function(xhr, status, error) {
                console.error('Error adding portfolio:', error);
                customAlert('新增组合失败');
            }
        });
    }

    function saveEditPortfolio() {
        const portfolioId = $('#editPortfolioId').val();
        const portfolioName = $('#editPortfolioName').val();
        const description = $('#editPortfolioDescription').val();

        if (portfolioName.trim() === '') {
            customAlert('组合名称不能为空');
            return;
        }

        const updatedPortfolio = {
            id: portfolioId,
            portfolioName: portfolioName,
            description: description
        };

        $.ajax({
            url: `/api/portfolios/updatePortfolio`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(updatedPortfolio),
            success: function(data) {
                $('#editPortfolioModal').modal('hide');
                fetchPortfolios();
                customAlert('信息更新成功');
            },
            error: function(xhr, status, error) {
                console.error('Error updating portfolio:', error);
                customAlert('更新组合信息失败');
            }
        });
    }

    function deletePortfolio(id) {
        if (confirm('确定要删除该投资组合吗？')) {
            $.ajax({
                url: `/api/portfolios/deletePortfolio/${id}`,
                type: 'POST',
                success: function() {
                    fetchPortfolios();
                    customAlert('删除成功');
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting portfolio:', error);
                    customAlert('删除组合失败');
                }
            });
        }
    }

    function showPortfolio(id) {
        $.ajax({
            url: `/api/portfolios/${id}`,
            type: 'GET',
            success: function(data) {
                selectedPortfolio = data;
                $('#detailPortfolioName').text(data.portfolioName);
                $('#detailPortfolioDescription').text(data.description || '');
                $('#detailPortfolioCreatedTime').text(data.createdTime || '');
                $('#detailPortfolioUpdatedTime').text(data.updatedTime || '');
                $('#detailPortfolioTotalValue').text(data.totalValue || '0.00');
                $('#detailPortfolioTotalCost').text(data.totalCost || '0.00');
                $('#detailPortfolioTotalProfit').text(data.totalProfit || '0.00');
                $('#detailPortfolioTotalProfitRate').text((data.totalProfitRate || 0) + '%');
                
                // 设置添加基金按钮的portfolioId
                $('#addFundToPortfolioButton').data('portfolio-id', id);
                $('#addFundPortfolioId').val(id);
                
                // 显示组合中的基金
                renderPortfolioFunds(data.funds || []);
                
                $('#detailPortfolioModal').modal('show');
            },
            error: function(xhr, status, error) {
                console.error('Error fetching portfolio details:', error);
                customAlert('获取组合详情失败');
            }
        });
    }

    function renderPortfolioFunds(funds) {
        const fundsTableBody = $('#portfolioFundsTableBody');
        fundsTableBody.empty();

        if (funds.length > 0) {
            funds.forEach(fund => {
                const tr = $('<tr>');
                tr.append($('<td>').text(fund.fundCode));
                tr.append($('<td>').text(fund.fundName));
                tr.append($('<td>').text(fund.shares));
                tr.append($('<td>').text(fund.buyPrice));
                tr.append($('<td>').text(fund.netValue || '0.0000'));
                tr.append($('<td>').text(fund.currentValue || '0.00'));
                tr.append($('<td>').text(fund.cost || '0.00'));
                tr.append($('<td>').text(fund.profit || '0.00'));
                tr.append($('<td>').text((fund.profitRate || 0) + '%'));
                
                const actionsTd = $('<td>');
                actionsTd.html(`
                    <button class="btn btn-sm btn-danger" onclick="removeFundFromPortfolio(${fund.portfolioId}, ${fund.id})">移除</button>
                `);
                tr.append(actionsTd);
                fundsTableBody.append(tr);
            });
        } else {
            fundsTableBody.html('<tr><td colspan="10" class="text-center">暂无基金</td></tr>');
        }
    }

    function addFundToPortfolio() {
        const portfolioId = $('#addFundPortfolioId').val();
        const fundCode = $('#addFundCode').val();

        if (fundCode.trim() === '') {
            customAlert('基金代码不能为空');
            return;
        }

        $.ajax({
            url: `/api/portfolios/addFundToPortfolio`,
            type: 'POST',
            data: {
                portfolioId: portfolioId,
                fundCode: fundCode,
                shares: "0",      // 不再需要这些参数
                buyPrice: "0",    // 但为了保持接口兼容性仍传递
                buyTime: ""       // 但为了保持接口兼容性仍传递
            },
            success: function(data) {
                $('#addFundForm')[0].reset();
                $('#addFundModal').modal('hide');
                // 刷新组合详情
                showPortfolio(portfolioId);
                customAlert('添加标的成功');
            },
            error: function(xhr, status, error) {
                console.error('Error adding fund to portfolio:', error);
                customAlert('添加标的失败');
            }
        });
    }

    function removeFundFromPortfolio(portfolioId, fundId) {
        if (confirm('确定要将该基金从组合中移除吗？')) {
            $.ajax({
                url: `/api/portfolios/removeFundFromPortfolio`,
                type: 'POST',
                data: {
                    portfolioId: portfolioId,
                    fundId: fundId
                },
                success: function() {
                    // 刷新组合详情
                    showPortfolio(portfolioId);
                    customAlert('移除基金成功');
                },
                error: function(xhr, status, error) {
                    console.error('Error removing fund from portfolio:', error);
                    customAlert('移除基金失败');
                }
            });
        }
    }

    // 全局函数供HTML调用
    window.editPortfolio = function(id) {
        const portfolio = portfolios.find(p => p.id == id);
        if (portfolio) {
            $('#editPortfolioId').val(portfolio.id);
            $('#editPortfolioName').val(portfolio.portfolioName);
            $('#editPortfolioDescription').val(portfolio.description || '');
            $('#editPortfolioModal').modal('show');
        }
    };

    window.deletePortfolio = deletePortfolio;
    window.showPortfolio = showPortfolio;
    window.removeFundFromPortfolio = removeFundFromPortfolio;

    // 事件绑定
    $('#fetchPortfoliosButton').on('click', fetchPortfolios);
    $('#saveAddPortfolio').on('click', addNewPortfolio);
    $('#saveEditPortfolio').on('click', saveEditPortfolio);
    $('#saveAddFund').on('click', addFundToPortfolio);

    $('#itemsPerPage').on('change', function() {
        handleSizeChange(parseInt($(this).val(), 10));
    });

    $('#pPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage > 1) {
            handleCurrentChange(currentPage - 1); 
        }
    });
    
    $('#nPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage < totalPages) {
            handleCurrentChange(currentPage + 1); 
        }
    });

    // 添加标的模态框显示时的处理
    $('#addFundModal').on('show.bs.modal', function (event) {
        const button = $(event.relatedTarget);
        const portfolioId = button.data('portfolio-id');
        $('#addFundPortfolioId').val(portfolioId);
        
        // 清空基金代码和名称
        $('#addFundCode').val('');
        $('#addFundName').val('');
    });

    // 基金代码输入框失去焦点时，自动获取基金名称
    $('#addFundCode').on('blur', function() {
        const fundCode = $(this).val();
        if (fundCode) {
            fetchFundsForSearch(fundCode, function(funds) {
                const fund = funds.find(f => f.fundCode === fundCode);
                if (fund) {
                    $('#addFundName').val(fund.fundName);
                } else {
                    $('#addFundName').val('');
                }
            });
        }
    });

    // 基金代码输入框键盘输入时，提供搜索建议
    let searchTimeout;
    $('#addFundCode').on('input', function() {
        const fundCode = $(this).val();
        clearTimeout(searchTimeout);
        
        if (fundCode.length >= 2) {
            searchTimeout = setTimeout(function() {
                fetchFundsForSearch(fundCode);
            }, 300);
        }
    });

    // 在页面加载时调用 fetchPortfolios 函数以获取并渲染数据
    fetchPortfolios();
});